<template lang="">
  <div>
    <el-card class="box-card">
      <!-- 顶部搜索 -->
        <el-row :gutter="6">
          <el-col :span="22">
            <el-form ref="formRef" :model="searchForm" label-width="80px">
              <el-form-item label="活动时间">
                <el-col :span="6">
                  <el-date-picker type="datetime" placeholder="开始时间" v-model="searchForm.startTime" style="width: 100%;"></el-date-picker>
                </el-col>
                <el-col :span="6">
                  <el-date-picker type="datetime" placeholder="结束时间" v-model="searchForm.endTime" style="width: 100%;"></el-date-picker>
                </el-col>
                <el-col :span="8">
                  <el-button type="primary" @click="doSearch">搜索</el-button>
                </el-col>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="showDialog">添加</el-button>
          </el-col>
        </el-row>
        <el-table
          :data="filterTableData"
          border
          style="width: 100%">

          <el-table-column
            label="序号"
            type="index"
            width="50">
          </el-table-column>

          <el-table-column
            prop="date"
            label="创建日期"
            width="180">
            <template slot-scope="scope">
              <span>{{scope.row.date | formatTime}}</span>
            </template>

          </el-table-column>


          <el-table-column
            prop="type"
            label="收支类型"
            width="180">
          </el-table-column>

          <el-table-column
            prop="describe"
            label="收支描述">
          </el-table-column>

           <el-table-column
            prop="income"
            label="收入">
          </el-table-column>

           <el-table-column
            prop="expend"
            label="支出">
          </el-table-column>
          <el-table-column
            prop="remark"
            label="描述">
          </el-table-column>

           <el-table-column
           width="160px"
            label="操作">
            
            <template slot-scope="scope">
  <el-button type="warning" size="small" @click="showUpdate(scope.row)">修改</el-button
  >
  <el-button type="danger" size="small" @click="handleDelete(scope.row._id)">删除</el-button>
</template>
           
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          :current-page="page"
          :page-sizes="[2,5,10]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
    </el-card>

    <!-- 弹框 -->
    <el-dialog
      :title="dialog.title"
      :visible.sync="dialogVisible"
      @close="closeDialog"
      width="50%">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="收支类型">
          <el-select v-model="form.type" placeholder="选择收支类型">
            <el-option label="提现" value="提现"></el-option>
            <el-option label="提现手续费" value="提现手续费"></el-option>
            <el-option label="充值" value="充值"></el-option>
            <el-option label="优惠券" value="优惠券"></el-option>
            <el-option label="充值礼券" value="充值礼券"></el-option>
            <el-option label="转账" value="转账"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="收支描述" prop="describe">
          <el-input v-model="form.describe"></el-input>
        </el-form-item>
        <el-form-item label="收入" prop="income">
          <el-input v-model="form.income"></el-input>
        </el-form-item>
        <el-form-item label="支出" prop="expend">
          <el-input v-model="form.expend"></el-input>
        </el-form-item>
        <el-form-item label="账户现金" prop="cash">
          <el-input v-model="form.cash"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doAdd" v-if="dialog.type=='add'">添 加</el-button>
        <el-button type="primary" @click="doUpdate" v-else>修 改</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>

export default {
  name: "FoudList",
  data() {
    return {
      dialog: {
        title: "添加资金信息",   //dialog标题：添加或修改资金信息
        type: "add",   //dialog类型：add:添加  update:修改
        //弹框相关
      },
      dialogVisible: false,
      form: {
        type: "",
        describe: "",
        income: "",
        expend: "",
        cash: "",
        remark: ""
      },
      rules: {
        describe: [
          {
            required: true,
            message: "收支描述不能为空",
            trigger: ["blur", "change"],
          },
        ],
        income: [
          {
            required: true,
            message: "收入不能为空",
            trigger: ["blur", "change"],
          },
        ],
        expend: [
          {
            required: true,
            message: "支出不能为空",
            trigger: ["blur", "change"],
          },
        ],
        cash: [
          {
            required: true,
            message: "账户现金不能为空",
            trigger: ["blur", "change"],
          },
        ],
      },
      //列表数据
      tableData: [],
      // filterTableData: [],
      //分页
      page: 1, //当前页
      pageSize: 5, //当前页条数
      //筛选
      searchForm: {
        startTime: "",
        endTime: "",
      },
    };
  },
  computed: {
    total() {
      return this.tableData.length;
    },
    //列表筛选
    filterTableData() {
      return this.tableData.filter((item, index) => {
        let start = (this.page - 1) * this.pageSize;
        let end = this.page * this.pageSize;
        return index >= start && index < end;
      });
    },
  },
  filters: {
    formatTime(val) {
      let time = new Date(val); //北京标准时间
      let year = time.getFullYear();
      let obj = {
        month: time.getMonth() + 1,
        day: time.getDate(),
        hour: time.getHours(),
        minute: time.getMinutes(),
        second: time.getSeconds(),
      };

      for (let i in obj) {
        obj[i] = obj[i] < 10 ? "0" + obj[i] : obj[i];
      }
      return `${year}-${obj.month}-${obj.day} ${obj.hour}:${obj.minute}:${obj.second}`;
    },
  },
  methods: {
    //删除
    async handleDelete(id) {
      //显示删除确认框
      let result = await this.$confirm("您确定要删除此记录吗？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (result === 'confirm') {
        //删除记录
        result = await this.$http({ url: `/api/profiles/delete/${id}`, method: "DELETE" }).catch(err => err)
        if (result.status === 200) {
          this.$message.success("删除成功")
          //获取最新记录

          // 用filter删除页面数据
          // this.tableData = this.tableData.filter(item => {
          //   return item._id !== id
          // })
          //删除页面数据
          let index = this.tableData.findIndex(item => item._id == id)
          this.tableData.splice(index, 1)



        } else {
          this.$message.error("删除失败")
        }
      }
    },
    //隐藏弹窗
    closeDialog() {
      // console.log("hello")
      var result = this.$refs.formRef.resetFields()
      // console.log(result)
      // console.log(this.$refs.formRef)

    },
    //显示修改dialog
    showUpdate(row) {
      this.dialog.title = "修改资金信息"
      this.dialog.type = "update"
      this.dialogVisible = true;
      this.form = row;
    },
    //执行修改
    doUpdate() {
      //1.验证表单
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) {
          return this.$message({ type: "error", message: "信息有误" });
        }
        //2.请求接口
        let result = await this.$http({
          url: `/api/profiles/edit/${this.form._id}`,
          method: "POST",
          data: this.form
        }).catch(err => err);

        // 隐藏dialog
        this.dialogVisible = false
      });
    },
    //显示添加弹框表单
    showDialog() {

      this.dialog.title = "添加资金信息";
      this.dialog.type = "add"
      this.dialogVisible = true;
      this.form = {
        type: "",
        describe: "",
        income: "",
        expend: "",
        cash: "",
        remark: "",
        id: "",
      }



    },
    //执行添加操作
    doAdd() {
      this.$refs.formRef.validate(async (valid) => {
        //1.验证表单
        if (!valid) {
          return this.$message({ type: "error", message: "信息有误" });
        }
        //2.请求接口
        let { data, status } = await this.$http({
          url: "/api/profiles/add",
          method: "POST",
          data: this.form,
        }).catch((err) => err);
        // console.log(result, "$$$$$");
        if (status !== 200) return this.$message.error("添加数据错误")
        this.tableData.push(data)

        //3.隐藏dialog
        this.dialogVisible = false;
      });
    },
    //执行搜索
    async doSearch() {
      let start = this.searchForm.startTime.getTime(); //时间戳
      let end = this.searchForm.endTime.getTime(); //时间戳

      //发送网络请求
      let { data: res } = await this.$http({ url: "/api/profiles" }).catch(
        (err) => err
      );
      this.tableData = res;

      this.tableData = this.tableData.filter((item) => {
        var time = new Date(item.date).getTime();
        return time >= start && time <= end;
      });
    },
    //改变当前页条数
    handleSizeChange(size) {
      this.pageSize = size;
    },
    //页码跳转
    handlePageChange(page) {
      this.page = page;
    },
    //获取列表数据
    async getList() {
      //获取列表数据
      let { data: res } = await this.$http({ url: "/api/profiles" }).catch(
        (err) => err
      );
      this.tableData = res;
    }
  },
  created() {
    this.getList()
  },
};
</script>
<style lang="less">
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>